# Create your views here.

from rest_framework.generics import GenericAPIView

from rest_framework.response import Response

from activity.models import Gathering
from activity.serializers import ActivitySerializer
from users.models import User


# 获取活动列表
class ActivityAPIView(GenericAPIView):
    queryset = Gathering.objects.all()
    serializer_class = ActivitySerializer

    def get(self, request):
        null = None
        query_set = self.get_queryset()
        serializer = self.get_serializer(query_set, many=True)
        return Response({
            'count': query_set.count(),
            'next': null,
            'previous': null,
            'results': serializer.data,

        })


# 获取活动详情
class ActivityListAPIView(GenericAPIView):
    serializer_class = ActivitySerializer
    lookup_field = 'id'

    def get(self, request, id):
        query_set = Gathering.objects.filter(id=id)
        serializer = self.get_serializer(query_set, many=True)
        return Response(serializer.data[0])


#  活动报名
class ActivityApplyAPIView(GenericAPIView):

    def post(self, request, id):
        user_id = request.user.id
        gat_data = Gathering.objects.filter(users__id=user_id).first()
        user_data = User.objects.filter(id=user_id).first()
        if gat_data:
            gat_data.users.clear()
            gat_data.save()
            return Response({"message": "报名取消", "success": True})
        else:
            data = Gathering.objects.filter(id=id).first()
            data.users.add(user_data)
            data.save()
            return Response({"message": "报名成功", "success": True})
